package com.ruoyi.mes.utils;

import com.google.gson.Gson;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.mes.vo.qualityinspection.QualityInspectionVo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 质检工具类
 */
public class QualityInspectionUtils {
    /**
     * 开始质检
     * @return
     */
    public static QualityInspectionVo qualityInspection() throws IOException {
        // 定义URL
        String apiUrl = "http://192.168.1.99:5001/api/verify";
        URL url = new URL(apiUrl);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为GET
        connection.setRequestMethod("GET");
        // 获取响应代码
        int responseCode = connection.getResponseCode();

        QualityInspectionVo qualityInspectionVo = null;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 关闭连接
            connection.disconnect();
            // 解析JSON数据并存储在对象中
            String responseData = response.toString();
            Gson gson = new Gson();
            QualityInspectionVo responseObject = gson.fromJson(responseData, QualityInspectionVo.class);

            qualityInspectionVo = new QualityInspectionVo();
            BeanUtils.copyProperties(responseObject, qualityInspectionVo);

        } else {
            System.out.println("HTTP请求失败，响应代码：" + responseCode);
        }

        return qualityInspectionVo;
    }
}

